<template>
  <div class="app-container home">
    <div v-if="isUser" class="user-dashboard">
      <!-- Banner Carousel -->
      <el-carousel height="400px" class="banner-carousel" indicator-position="outside">
        <el-carousel-item v-for="(item, index) in bannerItems" :key="index">
          <div class="banner-item" :style="{backgroundImage: `url(${item.image})`}">
            <!-- <div class="banner-content">
              <h2>{{item.title}}</h2>
              <p>{{item.description}}</p>
            </div> -->
          </div>
        </el-carousel-item>
      </el-carousel>

      <!-- Welcome Section -->
      <!-- <el-row type="flex" justify="center" align="middle" class="welcome-section">
        <el-col class="content-wrapper">
          <div class="welcome-content">
            <h2>欢迎使用疫苗预约微服务系统</h2>
            <div class="divider"></div>
            <p>
              欢迎使用疫苗预约微服务系统。本系统提供疫苗预约、接种管理等功能,帮助医疗机构更好地开展疫苗接种工作。
            </p>
          </div>
        </el-col>
      </el-row> -->

      <!-- Vaccination Info Section -->
      <div class="info-section">
        <h2 class="section-title">疫苗接种须知</h2>
        <div class="divider"></div>
        
        <el-row :gutter="20" class="info-cards">
          <el-col :xs="24" :sm="12" :md="8" v-for="(item, index) in vaccinationInfo" :key="index">
            <el-card class="info-card" shadow="hover">
              <div class="card-icon">
                <i :class="item.icon"></i>
              </div>
              <h3>{{item.title}}</h3>
              <p>{{item.content}}</p>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- Quick Access Section -->
      <div class="quick-access-section">
        <h2 class="section-title">快速预约</h2>
        <div class="divider"></div>
        
        <el-row :gutter="20" class="access-cards">
          <el-col :xs="24" :sm="12" :md="6" v-for="(item, index) in quickAccessItems" :key="index">
            <el-card class="access-card" shadow="hover" @click.native="navigateTo(item.route)">
              <div class="access-icon">
                <i :class="item.icon"></i>
              </div>
              <h3>{{item.title}}</h3>
              <p>{{item.description}}</p>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>

    <div v-else class="chart-container">
      <el-row :gutter="20">
        <el-col :span="12">
          <h2>疫苗库存统计</h2>
          <div class="chart-wrapper">
            <div ref="vaccineChart" style="height: 500px; width: 100%"></div>
          </div>
        </el-col>
        <el-col :span="12">
          <h2>各地区接种统计</h2>
          <div class="chart-wrapper">
            <div ref="locationChart" style="height: 500px; width: 100%"></div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { listVaccine } from "@/api/vaccine/vaccine"
import { listAppointmentVaccination } from "@/api/appointment/appointmentVaccination"

export default {
  name: "Index",
  data() {
    return {
      // 版本号
      version: "1.0.0",
      chartInstance: null,
      pieChartInstance: null,
      vaccineData: [], // 清空默认数据
      locationData: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100 // 设置为100条数据
      },
      // 轮播图数据
      bannerItems: [
        {
          title: "及时接种，保护健康",
          //description: "疫苗接种是预防疾病最有效的方式之一，请按时完成接种计划",
          image: require("@/assets/images/banner4.jpg")
        },
        {
          title: "便捷预约，无需排队",
         // description: "在线预约接种时间，减少等待，提高效率",
          image: require("@/assets/images/banner5.jpg")
        },
        {
          title: "专业接种，安全保障",
         // description: "我们拥有专业的医护团队，确保每一次接种安全可靠",
          image: require("@/assets/images/banner6.jpg")
        }
      ],
      // 疫苗接种须知
      vaccinationInfo: [
        {
          title: "接种前准备",
          icon: "el-icon-alarm-clock",
          content: "接种前请保持充足休息，避免剧烈运动。接种当天请携带有效身份证件和预约凭证，穿着方便露出上臂的衣物。"
        },
        {
          title: "接种注意事项",
          icon: "el-icon-warning-outline",
          content: "如有发热、急性疾病或慢性疾病急性发作期，请暂缓接种并咨询医生意见。接种后请在现场留观30分钟。"
        },
        {
          title: "接种后观察",
          icon: "el-icon-view",
          content: "接种后24-48小时内避免剧烈运动，保持接种部位清洁干燥，若出现持续发热或其他异常反应，请及时就医。"
        },
        {
          title: "特殊人群提示",
          icon: "el-icon-user",
          content: "孕妇、哺乳期妇女、免疫功能低下者等特殊人群接种前请咨询专业医生，评估接种风险与获益。"
        },
        {
          title: "儿童接种提示",
          icon: "el-icon-child",
          content: "儿童接种需由监护人陪同，并按照儿童免疫规划时间表进行，确保按时完成全程接种。"
        },
        {
          title: "接种记录保存",
          icon: "el-icon-document",
          content: "妥善保管接种记录，作为完成接种的证明，也便于追踪接种情况和不良反应监测。"
        }
      ],
      // 快速访问项
      quickAccessItems: [
        {
          title: "预约疫苗",
          description: "在线预约疫苗接种服务",
          icon: "el-icon-date",
          route: "/appointment/appointment"
        },
        {
          title: "禁忌查询",
          description: "查询个人接种禁忌",
          icon: "el-icon-document",
          route: "/checks/checks"
        },
        {
          title: "疫苗信息",
          description: "了解各类疫苗相关信息",
          icon: "el-icon-info",
          route: "/vaccine/vaccine"
        },
        {
          title: "查看证书",
          description: "查看接种证书",
          icon: "el-icon-service",
          route: "/appointmentList/appointmentVaccinationList"
        }
      ]
    };
  },
  computed: {
    isUser() {
      return this.$store.getters.roles.includes('user')
    }
  },
  mounted() {
    if (!this.isUser) {
      this.getVaccineData()
      this.getLocationData()
    }
  },
  beforeDestroy() {
    if (this.chartInstance) {
      this.chartInstance.dispose()
    }
    if (this.pieChartInstance) {
      this.pieChartInstance.dispose()
    }
  },
  methods: {
    // 获取疫苗数据
    getVaccineData() {
      listVaccine(this.queryParams).then(response => {
        // 处理接口返回的数据
        const vaccineList = response.rows || [];
        
        // 按疫苗名称分组并统计库存
        const stockMap = new Map();
        vaccineList.forEach(item => {
          const quantity = parseInt(item.quantity) || 0;
          if (stockMap.has(item.name)) {
            stockMap.set(item.name, stockMap.get(item.name) + quantity);
          } else {
            stockMap.set(item.name, quantity);
          }
        });

        // 转换为图表所需的数据格式
        this.vaccineData = Array.from(stockMap).map(([name, stock]) => ({
          name,
          stock
        }));

        // 初始化图表
        this.initChart();
      });
    },
    // 获取地区接种数据
    getLocationData() {
      listAppointmentVaccination({
        ...this.queryParams,
        status: '1' // 已接种状态
      }).then(response => {
        const appointmentList = response.rows || [];
        
        // 按地区统计接种数
        const locationMap = new Map();
        appointmentList.forEach(item => {
          if (locationMap.has(item.location)) {
            locationMap.set(item.location, locationMap.get(item.location) + 1);
          } else {
            locationMap.set(item.location, 1);
          }
        });

        this.locationData = Array.from(locationMap).map(([name, value]) => ({
          name,
          value
        }));

        this.initPieChart();
      });
    },
    initChart() {
      if (!this.vaccineData.length) {
        return;
      }

      this.chartInstance = echarts.init(this.$refs.vaccineChart);
      
      const option = {
        title: {
          text: '各类疫苗当前库存量',
          left: 'center',
          top: 20,
          textStyle: {
            fontSize: 20
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.vaccineData.map(item => item.name),
          axisLabel: {
            interval: 0,
            fontSize: 14,
            rotate: 45 // 斜着显示标签，防止文字重叠
          }
        },
        yAxis: {
          type: 'value',
          name: '库存数量',
          nameTextStyle: {
            fontSize: 14
          }
        },
        series: [
          {
            name: '库存数量',
            type: 'bar',
            barWidth: '40%',
            data: this.vaccineData.map(item => ({
              value: item.stock,
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#83bff6' },
                  { offset: 0.5, color: '#188df0' },
                  { offset: 1, color: '#188df0' }
                ])
              }
            })),
            label: {
              show: true,
              position: 'top',
              fontSize: 14
            }
          }
        ]
      };
      
      this.chartInstance.setOption(option);
    },
    initPieChart() {
      if (!this.locationData.length) {
        return;
      }

      this.pieChartInstance = echarts.init(this.$refs.locationChart);
      
      const option = {
        title: {
          text: '各地区接种数量统计',
          left: 'center',
          top: 20,
          textStyle: {
            fontSize: 20
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          top: 'middle'
        },
        series: [
          {
            name: '接种数量',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{b}: {c}例'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 16,
                fontWeight: 'bold'
              }
            },
            data: this.locationData
          }
        ]
      };
      
      this.pieChartInstance.setOption(option);
    },
    // 页面导航
    navigateTo(route) {
      this.$router.push(route);
    }
  }
};
</script>

<style scoped lang="scss">
.home {
  min-height: calc(100vh - 120px);
}

.user-dashboard {
  padding: 20px 0;
}

/* Banner Carousel */
.banner-carousel {
  margin-bottom: 40px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.banner-item {
  height: 100%;
  background-size: cover;
  background-position: center;
  position: relative;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: none;
  }
}

.banner-content {
  position: absolute;
  left: 10%;
  top: 50%;
  transform: translateY(-50%);
  color: #fff;
  max-width: 500px;
  
  h2 {
    font-size: 36px;
    margin-bottom: 20px;
    font-weight: 700;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
  }
  
  p {
    font-size: 18px;
    line-height: 1.5;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
  }
}

/* Section Titles */
.section-title {
  text-align: center;
  font-size: 32px;
  color: #303133;
  margin-bottom: 15px;
}

.divider {
  width: 80px;
  height: 5px;
  background: #409EFF;
  margin: 0 auto 40px;
  border-radius: 3px;
}

/* Welcome Section */
.welcome-section {
  margin-bottom: 60px;
}

.welcome-content {
  padding: 50px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
  text-align: center;
  max-width: 1000px;
  margin: 0 auto;
  
  h2 {
    margin: 0;
    font-size: 36px;
    font-weight: 600;
    color: #303133;
  }
  
  p {
    margin: 30px 0 0;
    font-size: 18px;
    line-height: 1.8;
    color: #606266;
  }
}

/* Info Section */
.info-section {
  margin-bottom: 60px;
  padding: 0 20px;
}

.info-cards {
  margin-bottom: 30px;
}

.info-card {
  height: 100%;
  transition: transform 0.3s;
  
  &:hover {
    transform: translateY(-5px);
  }
  
  .card-icon {
    font-size: 50px;
    color: #409EFF;
    margin-bottom: 20px;
    text-align: center;
  }
  
  h3 {
    font-size: 20px;
    margin-bottom: 15px;
    color: #303133;
    text-align: center;
  }
  
  p {
    font-size: 16px;
    line-height: 1.6;
    color: #606266;
    text-align: justify;
  }
}

/* Quick Access Section */
.quick-access-section {
  margin-bottom: 60px;
  padding: 0 20px;
}

.access-cards {
  margin-bottom: 30px;
}

.access-card {
  height: 100%;
  transition: all 0.3s;
  cursor: pointer;
  text-align: center;
  padding: 20px;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
    background: #f0f9ff;
  }
  
  .access-icon {
    font-size: 40px;
    color: #409EFF;
    margin-bottom: 15px;
  }
  
  h3 {
    font-size: 18px;
    margin-bottom: 10px;
    color: #303133;
  }
  
  p {
    font-size: 14px;
    color: #606266;
  }
}

/* Chart Container (Admin View) */
.chart-container {
  width: 100%;
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);

  h2 {
    text-align: center;
    margin-bottom: 30px;
    font-size: 32px;
    color: #303133;
  }

  .chart-wrapper {
    padding: 20px;
  }
}

/* Responsive Adjustments */
@media (max-width: 768px) {
  .banner-content {
    left: 5%;
    max-width: 90%;
    
    h2 {
      font-size: 28px;
    }
    
    p {
      font-size: 16px;
    }
  }
  
  .welcome-content {
    padding: 30px;
    
    h2 {
      font-size: 28px;
    }
    
    p {
      font-size: 16px;
    }
  }
  
  .section-title {
    font-size: 26px;
  }
}
</style>

